const API_BASE_URL = '/api'

export interface User {
  id: string
  email?: string
  phone?: string
  username?: string
  avatar_url?: string
  is_verified: boolean
  login_type: 'email' | 'phone' | 'oauth'
  created_at: string
  updated_at: string
  last_login_at?: string
}

export interface AuthResponse {
  success: boolean
  message: string
  user?: User
  token?: string
  refresh_token?: string
  error?: string
}

export interface VerificationResponse {
  success: boolean
  message: string
  code_id?: string
  error?: string
  dev_code?: string // 开发环境返回的验证码
}

class AuthAPI {
  private token: string | null = null

  constructor() {
    // 从localStorage加载token
    this.token = localStorage.getItem('auth_token')
  }

  // 设置认证token
  setToken(token: string | null) {
    this.token = token
    if (token) {
      localStorage.setItem('auth_token', token)
    } else {
      localStorage.removeItem('auth_token')
    }
  }

  // 获取请求头
  private getHeaders() {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json'
    }

    if (this.token) {
      headers['Authorization'] = `Bearer ${this.token}`
    }

    return headers
  }

  // 通用请求方法
  private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
    const url = `${API_BASE_URL}${endpoint}`
    
    const response = await fetch(url, {
      ...options,
      headers: {
        ...this.getHeaders(),
        ...options.headers
      }
    })

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.message || `HTTP ${response.status}`)
    }

    return response.json()
  }

  // 邮箱密码注册
  async registerWithEmail(email: string, password: string, username?: string): Promise<AuthResponse> {
    try {
      const response = await this.request<AuthResponse>('/auth/register/email', {
        method: 'POST',
        body: JSON.stringify({ email, password, username })
      })

      if (response.success && response.token) {
        this.setToken(response.token)
      }

      return response
    } catch (error) {
      return {
        success: false,
        message: error instanceof Error ? error.message : '注册失败',
        error: 'REGISTRATION_ERROR'
      }
    }
  }

  // 邮箱密码登录
  async loginWithEmail(email: string, password: string): Promise<AuthResponse> {
    try {
      const response = await this.request<AuthResponse>('/auth/login/email', {
        method: 'POST',
        body: JSON.stringify({ email, password })
      })

      if (response.success && response.token) {
        this.setToken(response.token)
      }

      return response
    } catch (error) {
      return {
        success: false,
        message: error instanceof Error ? error.message : '登录失败',
        error: 'LOGIN_ERROR'
      }
    }
  }

  // 发送手机验证码
  async sendPhoneVerificationCode(phone: string, type: 'login' | 'register' = 'login'): Promise<VerificationResponse> {
    try {
      return await this.request<VerificationResponse>('/auth/send-code', {
        method: 'POST',
        body: JSON.stringify({ phone, type })
      })
    } catch (error) {
      return {
        success: false,
        message: error instanceof Error ? error.message : '发送验证码失败',
        error: 'SEND_CODE_ERROR'
      }
    }
  }

  // 手机验证码登录/注册
  async loginWithPhone(phone: string, code: string, username?: string): Promise<AuthResponse> {
    try {
      const response = await this.request<AuthResponse>('/auth/login/phone', {
        method: 'POST',
        body: JSON.stringify({ phone, code, username })
      })

      if (response.success && response.token) {
        this.setToken(response.token)
      }

      return response
    } catch (error) {
      return {
        success: false,
        message: error instanceof Error ? error.message : '验证码登录失败',
        error: 'PHONE_LOGIN_ERROR'
      }
    }
  }

  // 获取用户信息
  async getCurrentUser(): Promise<{ success: boolean; user?: User; message?: string }> {
    try {
      if (!this.token) {
        return { success: false, message: '未登录' }
      }

      const response = await this.request<{ success: boolean; user: User }>('/auth/me')
      return response
    } catch (error) {
      // Token可能已过期，清除本地存储
      this.setToken(null)
      return {
        success: false,
        message: error instanceof Error ? error.message : '获取用户信息失败'
      }
    }
  }

  // 登出
  async logout(): Promise<{ success: boolean; message: string }> {
    try {
      if (this.token) {
        await this.request('/auth/logout', { method: 'POST' })
      }
      
      this.setToken(null)
      return { success: true, message: '登出成功' }
    } catch (error) {
      // 即使请求失败，也要清除本地token
      this.setToken(null)
      return { success: true, message: '登出成功' }
    }
  }

  // 检查是否已登录
  isLoggedIn(): boolean {
    return !!this.token
  }

  // 获取当前token
  getToken(): string | null {
    return this.token
  }
}

export const authAPI = new AuthAPI()
